package com.kimu.product_service_consumer.controller;

import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kimu.product_service_interface.entity.Product;
import com.kimu.product_service_interface.service.ProductService;
import com.kimu.user.entity.User;
import com.kimu.user.service.JwtService;
import com.kimu.user.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

@RestController
public class ProductController {

    @DubboReference
    private ProductService productService;

    @DubboReference
    private UserService userService;

    // jwt服务完全基于内存，速度快，不需要进行负载均衡调用，由服务器本身控制即可
    private JwtService jwtService;

    public ProductController(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    /*
     * 新增一个商品的接口，从HttpServletRequest中提取bearer token，验证token的有效性，并提取出username，再使用用户服务获取对应的用户
     */
    @PostMapping(path = "/api/products")
    public ResponseEntity<Product> createProduct(HttpServletRequest request, @RequestBody Product product) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        // 设置商品的用户id为user_id
        product.setUserId(user.getId());
        int row = productService.createProduct(product);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(product, HttpStatus.CREATED);
        }
    }

    /*
     * 获取一个商品的接口，获取商品不需要登录
     */
    @GetMapping(path = "/api/products/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable("id") Long id) {
        Product product = productService.getProductById(id);
        if (null == product) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(product, HttpStatus.OK);
        }
    }

    /*
     * 修改一个商品的接口，需要登录，并且商品必须是请求人的
     */
    @PutMapping(path = "/api/products/{id}")
    public ResponseEntity<Product> updateProduct(HttpServletRequest request, @RequestBody Product product) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        // 判断需要修改的商品是否属于请求用户
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Product oldProduct = productService.getProductById(product.getId());
        if (!oldProduct.getUserId().equals(user.getId())) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        // 属于该用户，再进行修改
        int row = productService.updateProduct(product);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(product, HttpStatus.OK);
        }
    }

    /*
     * 删除一个商品的接口，需要登录，并且商品必须是请求人的
     */
    @DeleteMapping(path = "/api/products/{id}")
    public ResponseEntity<Product> deleteProductById(HttpServletRequest request, @PathVariable("id") Long id) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Product oldProduct = productService.getProductById(id);
        if (oldProduct.getUserId().equals(user.getId())) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        // 使用逻辑删除，即将is_deleted设置为false，如果已经设置此字段为TableLogic则调用删除的方法
        int row = productService.deleteProductById(id);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(oldProduct, HttpStatus.OK);
        }
    }

    /*
     * 获取商品列表，不需要登录，使用分页进行查询，有页数和价格参数可以选择
     * @param pageNo 第几页
     * @param pageNum 这一页取多少个商品
     */
    @GetMapping(path = "/api/products")
    public ResponseEntity<List<Product>> getProducts(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageNum") Integer pageNum) {
        Page<Product> page = new Page<>(pageNo, pageNum);
        IPage<Product> result = productService.getProducts(
            page
        );
        List<Product> products = result.getRecords();
        return new ResponseEntity<>(products, HttpStatus.OK);
    }
}
